<template>
  <n-card :bordered="false" class="proCard">
    <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset">
      <template #statusSlot="{ model, field }">
        <n-input v-model:value="model[field]" />
      </template>
    </BasicForm>

    <BasicTable
      :columns="columns"
      :request="loadDataTable"
      :row-key="(row) => row.id"
      ref="actionRef"
      :actionColumn="actionColumn"
      @update:checked-row-keys="onCheckedRow"
      :scroll-x="1090"
    >
      <template #tableTitle>
        <n-button type="primary" @click="addTable">
          <template #icon>
            <n-icon>
              <PlusOutlined />
            </n-icon>
          </template>
          新建
        </n-button>
      </template>

      <template #toolbar>
        <n-button type="primary" @click="reloadTable">刷新数据</n-button>
      </template>
    </BasicTable>

    <n-modal v-model:show="showModal" :show-icon="false" preset="dialog" :title="editTitle">
      <!-- 更强大的防自动填充策略 -->
      <n-form
        :model="formParams"
        :rules="rules"
        ref="formRef"
        label-placement="left"
        :label-width="80"
        class="py-4"
        autocomplete="off"
      >
        <!-- 隐藏的假输入框，用于捕获浏览器的自动填充 -->
        <div style="position: absolute; opacity: 0; pointer-events: none;">
          <input type="text" name="fake_username" />
          <input type="password" name="fake_password" />
        </div>
        
        <n-form-item label="用户名" path="username">
          <n-input placeholder="请输入用户名" v-model:value="formParams.username" :disabled="usernameDisabled" autocomplete="off" name="admin_create_username" />
        </n-form-item>
        <!-- <n-form-item label="头像" path="avatar">
          <n-input placeholder="请输入头像" v-model:value="formParams.avatar" />
        </n-form-item> -->
        <n-form-item label="密码" path="password">
          <n-input type="password" placeholder="请输入密码" v-model:value="formParams.password" autocomplete="new-password" name="admin_create_password" />
        </n-form-item>
        <n-form-item label="描述" path="description">
          <n-input placeholder="请输入描述" v-model:value="formParams.description" />
        </n-form-item>
        <!-- <n-form-item label="昵称" path="nickName">
          <n-input placeholder="请输入昵称" v-model:value="formParams.nickName" />
        </n-form-item> -->
        <!-- <n-form-item label="全名" path="fullName">
          <n-input placeholder="请输入全名" v-model:value="formParams.fullName" />
        </n-form-item> -->
        <n-form-item label="手机号" path="mobile">
          <n-input placeholder="请输入手机号" v-model:value="formParams.mobile" />
        </n-form-item>
        <n-form-item label="邮箱" path="email">
          <n-input placeholder="请输入邮箱" v-model:value="formParams.email" />
        </n-form-item>
        <n-form-item label="角色" path="roleId">
          <n-select placeholder="请选择角色" v-model:value="formParams.roleId" :options="roleOptions">
          </n-select>
        </n-form-item>
        <!-- <n-form-item label="状态" path="status">
          <n-input placeholder="请输入状态" v-model:value="formParams.status" />
        </n-form-item> -->
      </n-form>

      <template #action>
        <n-space>
          <n-button @click="() => (showModal = false)">取消</n-button>
          <n-button type="info" :loading="formBtnLoading" @click="confirmForm">确定</n-button>
        </n-space>
      </template>
    </n-modal>
  </n-card>
</template>

<script lang="ts" setup>
  import { h, reactive, ref, computed } from 'vue';
  import { useDialog, useMessage } from 'naive-ui';
  import { BasicTable, TableAction } from '@/components/Table';
  import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
  import { getAdminPage, saveAdmin, updateAdmin, deleteAdmin } from '@/api/system/admin';
  import { getRoleList } from '@/api/system/role';
  import { columns } from './columns';
  import { PlusOutlined } from '@vicons/antd';
  import { ResultEnum } from '@/enums/httpEnum';

  const rules = {
    username: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入用户名',
    },
    avatar: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入头像',
    },
    password: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入密码',
    },
    description: {
      // required: true,
      trigger: ['blur', 'input'],
      message: '请输入描述',
    },
    // nickName: {
    //   // required: true,
    //   trigger: ['blur', 'input'],
    //   message: '请输入昵称',
    // },
    // fullName: {
    //   // required: true,
    //   trigger: ['blur', 'input'],
    //   message: '请输入全名',
    // },
    mobile: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入手机号',
    },
    email: {
      // required: true,
      trigger: ['blur', 'input'],
      message: '请输入邮箱',
    },
    status: {
      // required: true,
      trigger: ['blur', 'input'],
      message: '请输入状态',
    },
    roleId: {
      required: true,
      trigger: ['blur', 'change'],
      // 自定义验证函数，确保角色ID与选项匹配
      validator: (rule, value, callback) => {
        if (value === null || value === undefined || value === '') {
          callback(new Error('请选择角色'));
        } else {
          // 检查是否有匹配的选项
          if (roleOptions.value.length > 0) {
            // 尝试通过类型转换来匹配
            const stringValue = String(value);
            const hasMatch = roleOptions.value.some(option => 
              String(option.value) === stringValue
            );
            
            if (!hasMatch) {
              console.warn('角色ID不匹配选项:', value, '可用选项:', roleOptions.value);
            }
          }
          // 即使没有完全匹配，只要有值就通过验证
          callback();
        }
      },
    },
  };

  const schemas: FormSchema[] = [
    {
      field: 'username',
      component: 'NInput',
      label: '用户名',
      rules: [{ required: false }],
    },
    // {
    //   field: 'avatar',
    //   component: 'NInput',
    //   label: '头像',
    //   rules: [{ required: false }],
    // },
    // {
    //   field: 'password',
    //   component: 'NInput',
    //   label: '密码',
    //   rules: [{ required: false }],
    // },
    // {
    //   field: 'description',
    //   component: 'NInput',
    //   label: '描述',
    //   rules: [{ required: false }],
    // },
    // {
    //   field: 'nickName',
    //   component: 'NInput',
    //   label: '昵称',
    //   rules: [{ required: false }],
    // },
    // {
    //   field: 'fullName',
    //   component: 'NInput',
    //   label: '全名',
    //   rules: [{ required: false }],
    // },
    // {
    //   field: 'mobile',
    //   component: 'NInput',
    //   label: '手机号',
    //   rules: [{ required: false }],
    // },
    // {
    //   field: 'email',
    //   component: 'NInput',
    //   label: '邮箱',
    //   rules: [{ required: false }],
    // },
    // {
    //   field: 'status',
    //   component: 'NInput',
    //   label: '状态',
    //   rules: [{ required: false }],
    // },
  ];

  const formRef: any = ref(null);
  const message = useMessage();
  const actionRef = ref();

  const showModal = ref(false);
  const formBtnLoading = ref(false);
  const checkedAdminId = ref(); //当前编辑id
  const isEdit = ref(false); // 弹出框是否为编辑
  const dialog = useDialog();
  const editTitle = ref('');
  const usernameDisabled = ref(false); // 用户名是否禁用
  const formParams = reactive({
    id: null,
    username: '',
    avatar: '',
    password: '',
    description: '',
    nickName: '',
    fullName: '',
    mobile: '',
    email: '',
    status: 0,
    roleId: null, // 改为null以便与可能的数字类型ID匹配
  });
  const formParamsBak = { ...formParams };
  const roleList = ref([]); // 角色列表
  const roleOptions = computed(() => {
    if (!Array.isArray(roleList.value)) {
      console.warn('roleList不是数组类型:', roleList.value);
      return [];
    }
    // 添加类型安全检查和容错处理
    return roleList.value
      .filter(item => item && item.roleName && item.id !== undefined)
      .map(item => ({
        label: item.roleName,
        value: item.id
      }));
  });

  const params = ref({});

  const actionColumn = reactive({
    width: 220,
    title: '操作',
    key: 'action',
    fixed: 'right',
    render(record) {
      // 当用户名为admin时不显示编辑和删除按钮
      if (record.username === 'admin') {
        return null;
      }
      
      return h(TableAction as any, {
        style: 'button',
        actions: [
          {
            label: '编辑',
            onClick: handleEdit.bind(null, record),
          },
          {
            label: '删除',
            type: 'error',
            icon: 'ic:outline-delete-outline',
            onClick: handleDelete.bind(null, record),
          },
        ],
      });
    },
  });

  const [register, {}] = useForm({
    gridProps: { cols: '1 s:1 m:2 l:3 xl:4 2xl:4' },
    labelWidth: 100,
    schemas,
  });

  // 加载角色列表
  const loadRoleList = async () => {
    try {
      const response = await getRoleList();
      console.log('getRoleList响应数据:', response);
      // 更灵活的数据处理，适配不同的返回格式
      // 由于设置了isTransformResponse: false，需要处理完整的HTTP响应
      let data = response;
      
      // 如果响应是包含data字段的对象，尝试获取data
      if (response && response.data && typeof response.data === 'object') {
        data = response.data;
      }
      
      // 检查data格式并提取角色列表
      if (data && data.code === ResultEnum.SUCCESS) {
        if (data.result && data.result.list) {
          roleList.value = data.result.list;
        } else if (Array.isArray(data.result)) {
          roleList.value = data.result;
        } else if (Array.isArray(data.data)) {
          roleList.value = data.data;
        } else if (Array.isArray(data)) {
          roleList.value = data;
        } else {
          roleList.value = [];
          console.warn('未找到有效的角色列表数据');
        }
      } else if (Array.isArray(data)) {
        // 直接是角色数组的情况
        roleList.value = data;
      } else {
        roleList.value = [];
        console.warn('响应格式不匹配，未找到有效的角色列表数据');
      }
      console.log('处理后的roleList:', roleList.value);
    } catch (error) {
      console.error('加载角色列表时发生错误:', error);
      roleList.value = [];
      message.error('加载角色列表失败，请稍后重试');
    }
  };

  function addTable() {
    // 新增前清空表单 - 直接初始化所有字段以确保完全重置
    formParams.id = null;
    formParams.username = '';
    formParams.avatar = '';
    formParams.password = '';
    formParams.description = '';
    formParams.nickName = '';
    formParams.fullName = '';
    formParams.mobile = '';
    formParams.email = '';
    formParams.status = 0;
    formParams.roleId = null;
    
    isEdit.value = false;
    // 新增时用户名可修改
    usernameDisabled.value = false;
    // 加载角色列表
    loadRoleList();
    showModal.value = true;
    editTitle.value = '新增管理员';
  }

  const loadDataTable = async (res) => {
    console.log('res', res);
    return await getAdminPage({ ...params.value, ...res });
  };

  function onCheckedRow(rowKeys) {
    console.log(rowKeys);
  }

  function reloadTable() {
    actionRef.value.reload();
  }

  function confirmForm(e) {
    e.preventDefault();
    formBtnLoading.value = true;
    
    // 先确保roleId类型与选项值类型一致
    if (formParams.roleId !== null && formParams.roleId !== undefined && formParams.roleId !== '') {
      // 如果roleOptions中有选项，确保formParams.roleId与选项中的value类型匹配
      if (roleOptions.value.length > 0) {
        const firstOption = roleOptions.value[0];
        // 根据选项值的类型转换formParams.roleId
        if (typeof firstOption.value === 'number') {
          formParams.roleId = Number(formParams.roleId);
        } else if (typeof firstOption.value === 'string') {
          formParams.roleId = String(formParams.roleId);
        }
      }
    }
    
    console.log('提交前的formParams.roleId:', formParams.roleId, '类型:', typeof formParams.roleId);
    console.log('当前的roleOptions:', roleOptions.value);
    
    formRef.value.validate(async (errors) => {
      if (!errors) {
        let response;
        // 如果是编辑
        if (isEdit.value) {
          formParams.id = checkedAdminId.value;
          response = await updateAdmin(formParams);
        } else {
          response = await saveAdmin(formParams);
        }
        const { message: msg, code } = response;
        if (code == ResultEnum.SUCCESS) {
          message.success(msg);
          // 提交成功后直接重置所有表单字段
          formParams.id = null;
          formParams.username = '';
          formParams.avatar = '';
          formParams.password = '';
          formParams.description = '';
          formParams.nickName = '';
          formParams.fullName = '';
          formParams.mobile = '';
          formParams.email = '';
          formParams.status = 0;
          formParams.roleId = null;
          showModal.value = false;
          reloadTable();
        } else {
          message.error(msg);
        }
      } else {
        message.error('请填写完整信息');
      }
      formBtnLoading.value = false;
    });
  }

  function handleEdit(record: Recordable) {
    console.log('点击了编辑', record);
    checkedAdminId.value = record.id;
    // 创建一个不包含密码的新对象，避免密码被复制到表单
    const { password, ...recordWithoutPassword } = record;
    Object.assign(formParams, recordWithoutPassword);
    // 确保密码字段为空字符串
    formParams.password = '';
    // 编辑时用户名不可修改
    usernameDisabled.value = true;
    // 编辑时密码必填
    rules.password.required = true;
    // 加载角色列表
    loadRoleList().then(() => {
      // 确保角色ID类型与选项值类型一致
      if (record.roleId !== undefined && record.roleId !== null && record.roleId !== '') {
        // 首先将record.roleId设置到formParams
        formParams.roleId = record.roleId;
        
        // 确保roleOptions已准备好
        if (roleOptions.value && roleOptions.value.length > 0) {
          // 找到与record.roleId匹配的选项
          const matchingOption = roleOptions.value.find(option => 
            String(option.value) === String(record.roleId)
          );
          
          if (matchingOption) {
            // 如果找到匹配项，使用选项中的value类型
            formParams.roleId = matchingOption.value;
          } else {
            // 如果没有找到匹配项，尝试转换类型以匹配选项
            const firstOption = roleOptions.value[0];
            if (typeof firstOption.value === 'number') {
              formParams.roleId = Number(record.roleId);
            } else if (typeof firstOption.value === 'string') {
              formParams.roleId = String(record.roleId);
            }
          }
        }
        
        console.log('设置的角色ID类型和值:', typeof formParams.roleId, formParams.roleId);
        console.log('可用角色选项:', roleOptions.value);
      } else {
        formParams.roleId = null;
        console.log('记录中没有角色ID，设置为null');
      }
      
      // 确保角色信息已正确设置后再显示模态框
      showModal.value = true;
      isEdit.value = true;
      editTitle.value = `编辑管理员-${record.username}`;
    });
  }

  function handleDelete(record: Recordable) {
    console.log('点击了删除', record);
    dialog.info({
      title: '提示',
      content: `您确定想删除吗?`,
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: async () => {
        const params = { id: record.id };
        const response = await deleteAdmin(params);
        const { message: msg, code } = response;
        if (code == ResultEnum.SUCCESS) {
          message.success(msg);
          reloadTable();
        } else {
          message.error(msg);
        }
      },
      onNegativeClick: () => {
        message.error('已取消');
      },
    });
  }

  function handleSubmit(values: Recordable) {
    console.log(values);
    params.value = values;
    reloadTable();
  }

  function handleReset(values: Recordable) {
    console.log(values);
  }
</script>

<style lang="less" scoped></style>
